package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Sign;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.domain.Wallet;
import cn.wolfcode.trip.base.mapper.SignMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.mapper.WalletMapper;
import cn.wolfcode.trip.base.service.IWalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class WalletServiceImpl implements IWalletService{

    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SignMapper signMapper;

    public Wallet getBalanceByUserId(Long id) {
        return walletMapper.getBalanceByUserId(id);
    }

    public void updateBalance(Wallet wallet) {
        User user = userMapper.selectByPrimaryKey(wallet.getUser().getId());
        wallet.setIntegral(wallet.getIntegral()+user.getIntegral().intValue());
        user.setIntegral(new BigDecimal(wallet.getIntegral()));
        walletMapper.updateBalance(wallet);
        userMapper.updateIntegral(user);
        Sign sign = new Sign();
        sign.setState(1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = dateFormat.format(new Date());
        try {
            Date date = dateFormat.parse(format);
            sign.setSignTime(date);
            signMapper.updateState(sign);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
